#pragma once
#include "uart/ProtocolSender.h"
#include "utils/BrightnessHelper.h"
#include "utils/TimeHelper.h"
#include "storage/StoragePreferences.h"
#include "water/self_mode.h"
#include "logic_utility.hpp"
#include <base/time.hpp>
#include<thread>
#include "zkota/UpdateSolver.h"
#include "zkota/version.h"
#include "manager/Lock.h"
#include "uart/ProtocolCustom.h"
#include "net/NetManager.h"
#include <iomanip>  // std::fixed, std::setprecision
#include <sstream>  // std::ostringstream




//低沸点
static int boiling_point = 0;
static std::string PassWard="0308";

#define WIFIMANAGER			NETMANAGER->getWifiManager()
//用户输入密码
std::string PassWardUser="";
namespace {
//工厂模式线程
class FactoryMode: public Thread {
public:
  virtual bool readyToRun() {

    return true;
  }
  virtual bool threadLoop() {
	  Count++;
	  mTextView12Ptr->setText((360-Count));
    //为了方便观察，这里添加休眠1000ms
    for(unsigned int i=0;i<100;i++){
    	//检查是否有退出线程的请求，如果有，则返回false，立即退出线程
        if (exitPending()) {
          return false;
        }
    	 usleep(1000 * 10);
    }
    //返回真，继续下次线程循环
    return true;
  }
  int Count;//倒计时

  /*
   * @breif 返回倒计时
   */
  int RetCount(){
	  return Count;
  }
};
static FactoryMode factoryMode;
};

//滑块监听
namespace
{
class MyISeekBarChangeListener: public ZKSeekBar ::ISeekBarChangeListener
{
		 virtual void onProgressChanged(ZKSeekBar *pSeekBar, int progress)
		 {
			char brightStr[16];
			sprintf(brightStr,"%d%%",progress);
			mTextViewBrigValuePtr->setText(brightStr);

			BRIGHTNESSHELPER->setBrightness(progress);
		 }
		virtual void onStartTrackingTouch(ZKSeekBar *pSeekBar) {

		}
		virtual void onStopTrackingTouch(ZKSeekBar *pSeekBar) {
		}
};
}
static MyISeekBarChangeListener lightSeekBarChangeListener;

//static int getProgress_text(int progress, int max_progress, int progress_len)
//{
//    int p = (progress * progress_len) / max_progress;
//    return p;
//}

//滑块监听
namespace
{
class FEIISeekBarChangeListener: public ZKSeekBar ::ISeekBarChangeListener
	 {
		 virtual void onProgressChanged(ZKSeekBar *pSeekBar, int progress)
		 {
				boiling_point = 80 + progress * 1;
				mTempFeiDianPtr->setText(to_string(boiling_point) + "℃");
//				LayoutPosition pos = mTempFeiDianPtr->getPosition();
//				LOGD("progress == %d",progress);
//				pos.mLeft = 138 + getProgress_text(progress, pSeekBar->getMax(), pSeekBar->getPosition().mWidth - pos.mWidth);
//				mTempFeiDianPtr->setPosition(pos);
		 }
			virtual void onStartTrackingTouch(ZKSeekBar *pSeekBar) {

			}
			virtual void onStopTrackingTouch(ZKSeekBar *pSeekBar) {
			}
};
}
static FEIISeekBarChangeListener feiISeekBarChangeListener;
//重启线程
namespace{
class MyReboot: public Thread {
public:
  virtual bool readyToRun() {
    LOGD("重启Thread 已经创建完成");
    return true;
  }

  virtual bool threadLoop() {
    //为了方便观察，这里添加休眠500ms
    usleep(1000 * 1500);
    SHELL("reboot");
//    system("reboot");
    //返回真，继续下次线程循环
    return true;
  }
};
static MyReboot myReboot;
}

static void setSystemTime(int year, int mon, int day, int hour, int min, int sec) {
	struct tm t;
	t.tm_year = year - 1900;//年
	t.tm_mon = mon - 1;			//月
	t.tm_mday = day;				//日
	t.tm_hour = hour;		//时
	t.tm_min = min;		//分
	t.tm_sec = sec;		//秒
	TimeHelper::setDateTime(&t);
}

void operateResetDevice() {
    StoragePreferences::clear();
    water::clear_self_mode();
    //删除WiFi信息
    SHELL("rm /data/misc/wifi/wpa_supplicant.conf");
    //自定义记忆变量
    SHELL("rm /data/costom.json");
//    system("rm /data/misc/wifi/wpa_supplicant.conf");
    //重置时间
    setSystemTime(2022,1,1,0,0,0);

	//关掉负载
    protocol::closeAllValve();
    protocol::stopOutputWater();
	//1.5s重启
	myReboot.run();
}


namespace { // 加个匿名作用域，防止多个源文件定义相同类名，运行时冲突

//实现长按监听接口
class LongClickListener : public ZKBase::ILongClickListener {

         virtual void onLongClick(ZKBase *pBase) {
                LOGD("触发长按事件");
                mFactoryPassWndPtr->showWnd();
            	PassWardUser="";
                EASYUICONTEXT->hideStatusBar();

         }
};
static LongClickListener longButtonClickListener;

}

namespace {

std::thread update_thread;

void updateVersionString() {
  auto t = base::buildDateTime();
  auto str = base::format("ZZZ-%02d%02d%02d%02d%02d",
  t.year % 100, t.month, t.day, t.hour, t.min);
  mVersionTipPtr->setText(str);
  mVersionTip1Ptr->setText(str);
}

std::thread startUpdate() {
  Global::Flags::is_updating = true;
  mTextViewUpdateMessagePtr->setText("软件更新中，请稍后");
  protocol::closeAllValve();
  protocol::stopOutputWater();
//  mTextViewUpdateMessagePtr->setTextColor(0xff000000);

  return std::thread([]() {
    try {
      updateProcessing( [](int64_t dltotal, int64_t dlnow, int64_t ultotal, int64_t ulnow) {
        if (dltotal == 0) {
          mOtaBarPtr->setProgress(0);
          return Global::Flags::is_updating;
        }
        mOtaBarPtr->setProgress(int(dlnow * 100.0 / dltotal));
        return Global::Flags::is_updating;
      });
    } catch (std::exception& e) {
      mTextViewUpdateMessagePtr->setTextColor(0xffff0000);
      mTextViewUpdateMessagePtr->setText(e.what());
      Thread::sleep(3000);
    }
    mOtaWndPtr->setVisible(false);
    Global::Flags::is_updating = false;
    EASYUICONTEXT->showStatusBar();
  });
}

void stopUpdate() {
  Global::Flags::is_updating = false;
  if (update_thread.joinable()) {
    update_thread.join();
  }
}

} /* anonymous namespace */
/**
 * 注册定时器
 * 填充数组用于注册定时器
 * 注意：id不能重复
 */
static S_ACTIVITY_TIMEER REGISTER_ACTIVITY_TIMER_TAB[] = {
	//{0,  6000}, //定时器id=0, 时间间隔6秒
	//{1,  1000},
};

/**
 * 当界面构造时触发
 */
static void onUI_init(){

	mlightBarPtr->setSeekBarChangeListener(&lightSeekBarChangeListener);
	mSeekBar2Ptr->setSeekBarChangeListener(&feiISeekBarChangeListener);
	EASYUICONTEXT->showStatusBar();
	mTempFeiDianPtr->setTouchPass(true);
	mTextView12Ptr->setTouchPass(true);
	mTextViewBrigValuePtr->setTouchPass(true);
    mButton4Ptr->setLongClickListener(&longButtonClickListener);
    mlocktimePtr->setTouchPass(true);

}

//字符串添加
static void AddStr(std::string p){
	PassWardUser+=p;
	mTextView17Ptr->setText(PassWardUser);
}
//删除字符串
static void DelStr(){
	if(PassWardUser.size() > 0){
		PassWardUser=PassWardUser.substr(0, PassWardUser.length()-1);
	}
	mTextView17Ptr->setText(PassWardUser);
}

/**
 * 当切换到该界面时触发
 */
static void onUI_intent(const Intent *intentPtr) {
    if (intentPtr != NULL) {
        //TODO
    }
}

/*
 * 当界面显示时触发
 */
static void onUI_show() {
	updateVersionString();
	mlightBarPtr->setProgress(BRIGHTNESSHELPER->getBrightness());

    startCheckNewVersion(APP_GROW_NAME, [](const VersionInformation& info) {
    	if(info.is_newer){
    	      //有新版本
//    		mVersionTipNewPtr->setText(info.version);
//    	      mNewVersionWndPtr->setVisible(true);
//    	      mUpdateWndPtr->hideWnd();
    		mTextNewMaxPtr->setVisible(false);
    		mButtonStartUpdatePtr->setVisible(true);
    	}else{
    		mTextNewMaxPtr->setVisible(true);
    		mButtonStartUpdatePtr->setVisible(false);
    	}

    });
}

/*
 * 当界面隐藏时触发
 */
static void onUI_hide() {

}

/*
 * 当界面完全退出时触发
 */
static void onUI_quit() {
	mlightBarPtr->setSeekBarChangeListener(NULL);
	mSeekBar2Ptr->setSeekBarChangeListener(NULL);
    mButton4Ptr->setLongClickListener(NULL);
}

/**
 * 串口数据回调接口
 */
static void onProtocolDataUpdate(const SProtocolData &data) {

}

/**
 * 定时器触发函数
 * 不建议在此函数中写耗时操作，否则将影响UI刷新
 * 参数： id
 *         当前所触发定时器的id，与注册时的id相同
 * 返回值: true
 *             继续运行当前定时器
 *         false
 *             停止运行当前定时器
 */
static bool onUI_Timer(int id){
	switch (id) {

		default:
			break;
	}
    return true;
}

/**
 * 有新的触摸事件时触发
 * 参数：ev
 *         新的触摸事件
 * 返回值：true
 *            表示该触摸事件在此被拦截，系统不再将此触摸事件传递到控件上
 *         false
 *            触摸事件将继续传递到控件上
 */
static bool onsetActivityTouchEvent(const MotionEvent &ev) {
    switch (ev.mActionStatus) {
		case MotionEvent::E_ACTION_DOWN://触摸按下
			//LOGD("时刻 = %ld 坐标  x = %d, y = %d", ev.mEventTime, ev.mX, ev.mY);
			break;
		case MotionEvent::E_ACTION_MOVE://触摸滑动
			break;
		case MotionEvent::E_ACTION_UP:  //触摸抬起
			break;
		default:
			break;
	}
	return false;
}
static bool onButtonClick_iceCake(ZKButton *pButton) {
    LOGD(" ButtonClick iceCake !!!\n");
    EASYUICONTEXT->openActivity("iceMakingActivity");
    return false;
}

static bool onButtonClick_iceWater(ZKButton *pButton) {
    LOGD(" ButtonClick iceWater !!!\n");
    EASYUICONTEXT->openActivity("coldWaterActivity");
    return false;
}

static bool onButtonClick_restore(ZKButton *pButton) {
    LOGD(" ButtonClick restore !!!\n");
    mResfFctSettingsPtr->showWnd();
    return false;
}

static bool onButtonClick_filter(ZKButton *pButton) {
    LOGD(" ButtonClick filter !!!\n");
    return false;
}

static bool onButtonClick_boilingPoint(ZKButton *pButton) {
    LOGD(" ButtonClick boilingPoint !!!\n");
    mBoilingpointWndPtr->showWnd();
    boiling_point = StoragePreferences::getInt("BoilingPoint", 95);

	mSeekBar2Ptr->setProgress(boiling_point - 80);
    mTempFeiDianPtr->setText(to_string(boiling_point) + "℃");
    return false;
}

static bool onButtonClick_waterMode(ZKButton *pButton) {
    LOGD(" ButtonClick waterMode !!!\n");
    return false;
}

static bool onButtonClick_lock(ZKButton *pButton) {
    LOGD(" ButtonClick lock !!!\n");
    int progress = StoragePreferences::getInt("LockTime", SCREEN_LOCK_TIME) / 30 - 1;
    mlockSwitchPtr->setSelected(LOCK_SCREEN->getLockOpen());
    mlockBarPtr->setProgress(progress);
    mlockWndPtr->showWnd();
    return false;
}

static bool onButtonClick_light(ZKButton *pButton) {
    LOGD(" ButtonClick light !!!\n");
    EASYUICONTEXT->openActivity("ledActivity");
    return false;
}

static bool onButtonClick_touchSound(ZKButton *pButton) {
    LOGD(" ButtonClick touchSound !!!\n");
	msoundSwitchPtr->setSelected(Global::Flags::TouchSound);
	msoundWndPtr->showWnd();
    return false;
}

static bool onButtonClick_wifi(ZKButton *pButton) {
    LOGD(" ButtonClick wifi !!!\n");
    EASYUICONTEXT->openActivity("wifiActivity");
    return false;
}

static bool onButtonClick_time(ZKButton *pButton) {
    LOGD(" ButtonClick time !!!\n");
    EASYUICONTEXT->openActivity("timeActivity");
    return false;
}

static void onProgressChanged_lightBar(ZKSeekBar *pSeekBar, int progress) {
    //LOGD(" ProgressChanged lightBar %d !!!\n", progress);
}

static bool onButtonClick_Button4(ZKButton *pButton) {
    LOGD(" ButtonClick Button4 !!!\n");
    return false;
}

static bool onButtonClick_ButtonStartUpdate(ZKButton *pButton) {
    LOGD(" ButtonClick ButtonStartUpdate !!!\n");
    mUpdateWndPtr->showWnd();
    return false;
}
static bool onButtonClick_Button1(ZKButton *pButton) {
    LOGD(" ButtonClick Button1 !!!\n");
    mFactoryModeWndPtr->hideWnd();
    factoryMode.requestExit();

	LOCK_SCREEN->set_auto_count(true);
    water::stop_timer_event(E_TIMER_EVENT_WATER_CHECK_PRESS_TEST);
    EASYUICONTEXT->showStatusBar();
    return false;
}

static bool onButtonClick_Button2(ZKButton *pButton) {
    LOGD(" ButtonClick Button2 !!!\n");
    factoryMode.run();
    LOCK_SCREEN->set_auto_count(false);
    water::start_timer_event(E_TIMER_EVENT_WATER_CHECK_PRESS_TEST);
    return false;
}

static bool onButtonClick_Button25(ZKButton *pButton) {
    LOGD(" ButtonClick Button25 !!!\n");
    AddStr("1");
    return false;
}

static bool onButtonClick_Button26(ZKButton *pButton) {
    LOGD(" ButtonClick Button26 !!!\n");
    AddStr("2");
    return false;
}

static bool onButtonClick_Button27(ZKButton *pButton) {
    LOGD(" ButtonClick Button27 !!!\n");
    AddStr("3");
    return false;
}

static bool onButtonClick_Button28(ZKButton *pButton) {
    LOGD(" ButtonClick Button28 !!!\n");
    AddStr("4");
    return false;
}

static bool onButtonClick_Button29(ZKButton *pButton) {
    LOGD(" ButtonClick Button29 !!!\n");
    AddStr("5");
    return false;
}

static bool onButtonClick_Button30(ZKButton *pButton) {
    LOGD(" ButtonClick Button30 !!!\n");
    AddStr("6");
    return false;
}

static bool onButtonClick_Button31(ZKButton *pButton) {
    LOGD(" ButtonClick Button31 !!!\n");
    AddStr("7");
    return false;
}

static bool onButtonClick_Button32(ZKButton *pButton) {
    LOGD(" ButtonClick Button32 !!!\n");
    AddStr("8");
    return false;
}

static bool onButtonClick_Button33(ZKButton *pButton) {
    LOGD(" ButtonClick Button33 !!!\n");
    AddStr("9");
    return false;
}

static bool onButtonClick_Button34(ZKButton *pButton) {
    LOGD(" ButtonClick Button34 !!!\n");
    AddStr("0");
    return false;
}

static bool onButtonClick_Button36(ZKButton *pButton) {
    LOGD(" ButtonClick Button36 !!!\n");
    DelStr();
    return false;
}


static bool onButtonClick_Button35(ZKButton *pButton) {
    LOGD(" ButtonClick Button35 !!!\n");
    if(PassWard == PassWardUser){
    	mFactoryModeWndPtr->showWnd();
    	mFactoryPassWndPtr->hideWnd();
    }
    return false;
}

static bool onButtonClick_Button3(ZKButton *pButton) {
    LOGD(" ButtonClick Button3 !!!\n");
    mFactoryPassWndPtr->hideWnd();
	LOCK_SCREEN->set_auto_count(true);
    EASYUICONTEXT->showStatusBar();
    return false;
}



static void onProgressChanged_SeekBar2(ZKSeekBar *pSeekBar, int progress) {
    //LOGD(" ProgressChanged SeekBar2 %d !!!\n", progress);

}

static bool onButtonClick_BoilingYes(ZKButton *pButton) {
    LOGD(" ButtonClick BoilingYes !!!\n");
    StoragePreferences::putInt("BoilingPoint",boiling_point);

    mBoilingpointWndPtr->hideWnd();
    return false;
}

static bool onButtonClick_Boilingpoint(ZKButton *pButton) {
    LOGD(" ButtonClick Boilingpoint !!!\n");
    mBoilingpointWndPtr->hideWnd();
    return false;
}
static void onProgressChanged_OtaBar(ZKSeekBar *pSeekBar, int progress) {
    //LOGD(" ProgressChanged OtaBar %d !!!\n", progress);
	char brightStr[16];
	sprintf(brightStr,"%d%%",progress);
	mTextupdateValuePtr->setText(brightStr);
}

static bool onButtonClick_UpdateOkButton(ZKButton *pButton) {
    LOGD(" ButtonClick UpdateOkButton !!!\n");
    mOtaWndPtr->showWnd();
    stopUpdate();
    update_thread = startUpdate();
    return false;
}
static bool onButtonClick_boiling_back(ZKButton *pButton) {
    LOGD(" ButtonClick boiling_back !!!\n");
    mBoilingpointWndPtr->hideWnd();
    return false;
}

static bool onButtonClick_hide1(ZKButton *pButton) {
    LOGD(" ButtonClick hide1 !!!\n");
    mVersionTip0Ptr->setText("版本信息");
    mUpdateWndPtr->setVisible(false);
    return false;
}

static bool onButtonClick_checkupdate(ZKButton *pButton) {
    LOGD(" ButtonClick checkupdate !!!\n");
    mOtaWndPtr->showWnd();
    stopUpdate();
    update_thread = startUpdate();
    return false;
}

static bool onButtonClick_reset(ZKButton *pButton) {
    LOGD(" ButtonClick reset !!!\n");
    mResfFctSettingsPtr->hideWnd();
    operateResetDevice();
    return false;
}

static bool onButtonClick_hide2(ZKButton *pButton) {
    LOGD(" ButtonClick hide2 !!!\n");
    mResfFctSettingsPtr->hideWnd();
    return false;
}
static bool onButtonClick_hideNew(ZKButton *pButton) {
    LOGD(" ButtonClick hideNew !!!\n");
    mNewVersionWndPtr->setVisible(false);
    return false;
}

static bool onButtonClick_Button5(ZKButton *pButton) {
    LOGD(" ButtonClick Button5 !!!\n");
    if(msoundSwitchPtr->isSelected()){
    	Global::Flags::TouchSound = true;
    }else{
    	Global::Flags::TouchSound = false;
    }
    StoragePreferences::putBool("TouchSound", Global::Flags::TouchSound);
    msoundWndPtr->hideWnd();
    return false;
}

static bool onButtonClick_Button6(ZKButton *pButton) {
    LOGD(" ButtonClick Button6 !!!\n");
    msoundWndPtr->hideWnd();
    return false;
}

static bool onButtonClick_Button_back(ZKButton *pButton) {
    LOGD(" ButtonClick Button_back !!!\n");
    msoundWndPtr->hideWnd();
    return false;
}
static bool onButtonClick_soundSwitch(ZKButton *pButton) {
    LOGD(" ButtonClick soundSwitch !!!\n");
    pButton->setSelected(!pButton->isSelected());
    return false;
}
static bool onButtonClick_lockSwitch(ZKButton *pButton) {
    LOGD(" ButtonClick lockSwitch !!!\n");
    pButton->setSelected(!pButton->isSelected());
    LOCK_SCREEN->setLockOpen(pButton->isSelected());
    return false;
}

static void onProgressChanged_lockBar(ZKSeekBar *pSeekBar, int progress) {
    LOGD_TRACE(" ProgressChanged lockBar %d !!!\n", progress);
	float locktime = (progress + 1)* 30 / 60.0f;
    // 使用 ostringstream 格式化为字符串
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(1) << locktime;
    mlocktimePtr->setText(oss.str() + "分钟");
}

static bool onButtonClick_Button8(ZKButton *pButton) {
    LOGD(" ButtonClick Button8 !!!\n");
    SCREEN_LOCK_TIME = (mlockBarPtr->getProgress() + 1 )*30;
    StoragePreferences::putInt("LockTime", SCREEN_LOCK_TIME);
    mlockWndPtr->hideWnd();
    return false;
}

static bool onButtonClick_Button9(ZKButton *pButton) {
    LOGD(" ButtonClick Button9 !!!\n");
    mlockWndPtr->hideWnd();
    return false;
}

static bool onButtonClick_Button10(ZKButton *pButton) {
    LOGD(" ButtonClick Button10 !!!\n");
    mlockWndPtr->hideWnd();
    return false;
}
